/**
 * COPYRIGHT. Harry Wu 2011. ALL RIGHTS RESERVED.
 * Project: just-core
 * Author: Harry Wu <harrywu304@gmail.com>
 * Created On: Aug 10, 2011 4:35:08 PM
 *
*/ 
package org.justframework.core;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.Map;

import org.justframework.api.connector.Request;
import org.justframework.core.helper.ConfigHelper;
import org.justframework.core.helper.HostRouteHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * rendering uri for resourceId uri and host routing 
 *
 */
public class RequestRender {
	
	/**
	 * logger
	 */
	private static Logger logger = LoggerFactory.getLogger(RequestRender.class);
	
	/**
	 * resourceid uri mapping
	 */
	private static Map<String, String> resUriMapping;
	
	static {
		//get resourceid uri mapping
		resUriMapping = ConfigHelper.getMap("resource_uri_mapping");
	}
	
	public static void renderRequest(Request request){
		//update uri for resource id
		updateUriForResourceId(request);
		//update uri for routing target host
		updateUriForHostRouting(request);
		logger.debug("rendered new uri [{}]", request.getUri());
	}
	
	/**
	 * update uri for resource id
	 * @param request
	 */
	private static void updateUriForResourceId(Request request){
		String schema = request.getUri().getScheme();
		if(schema == null){
			String initUriStr = request.getUri().toString();
			String realUriStr = resUriMapping.get(initUriStr);
			try {
				URI realUri = new URI(realUriStr);
				//re-set request uri
				request.setUri(realUri);
			} catch (URISyntaxException e) {
				logger.error("Mapping uri is invalid [{}]", realUriStr, e);
			}
		}		
	}
	
	/**
	 * update uri for routing target host
	 * @param request
	 */
	private static void updateUriForHostRouting(Request request) {
		String host = request.getUri().getHost();
		if(host.contains(".") || "localhost".equalsIgnoreCase(host)){
			;
		} else {
			String serviceId = host;
			URI oldUri = request.getUri();
			
			//route to real host 
			host = HostRouteHelper.route(serviceId, oldUri.getScheme(), request.getRouteKeys());
			
			URI newUri = null;
			try {
				newUri = new URI(oldUri.getScheme(),host,oldUri.getPath(), oldUri.getQuery(), 
						oldUri.getFragment());
				//re-set request uri
				request.setUri(newUri);
			} catch (URISyntaxException e) {
				logger.error("construct new uri with new host fail",e);
			}			
		}
	}
	
}
